import React, { useState, useEffect } from 'react';
import {
  Button,
  Table,
  Space,
  Popconfirm,
  message,
  Input,
  Form,
  Modal,
  Select,
  InputNumber,
  Upload
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  UploadOutlined
} from '@ant-design/icons';
import { getProductPlaceholder } from '../../utils/imageUtils';
import './ProductManage.css';
import { getProducts, getCategories, updateProducts, deleteProducts } from '../../api/dashboard';
import { useRequest } from 'ahooks';

const { Option } = Select;

const ProductManage = () => {
  const [products, setProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [searchText, setSearchText] = useState('');

  const { runAsync: fetchProducts } = useRequest(getProducts, { manual: true });
  const { runAsync: fetchCategories } = useRequest(getCategories, { manual: true });
  const { runAsync: updateProduct } = useRequest(updateProducts, { manual: true });
  const { runAsync: deleteProduct } = useRequest(deleteProducts, { manual: true });


  const fetchData = async () => {
    const id = localStorage.getItem('adminUser').id || 1 ;
    // 从本地存储获取商品数据
    const storedProducts = await fetchProducts({params: { id: id } });
    setProducts(storedProducts);
    const storedCategories = await fetchCategories({params: { id: id } });
    setCategories(storedCategories);
  }
  // 获取商品和分类数据
  useEffect(() => {
    setLoading(true);
    fetchData();
    setLoading(false);
  }, []);

  // 获取分类名称
  const getCategoryName = (categoryId) => {
    const category = categories.find(c => c.id === categoryId);
    return category ? category.name : '未分类';
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 70
    },
    {
      title: '商品图片',
      dataIndex: 'images',
      key: 'images',
      width: 100,
      render: (images) => (
        <img
          src={images[0]}
          alt="商品图片"
          style={{ width: 50, height: 50, objectFit: 'cover' }}
        />
      )
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
      filteredValue: [searchText],
      onFilter: (value, record) =>
        record.name.toLowerCase().includes(value.toLowerCase())
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId) => getCategoryName(categoryId),
      filters: categories.map(cat => ({ text: cat.name, value: cat.id })),
      onFilter: (value, record) => record.categoryId === value
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price.toFixed(2)}`,
      sorter: (a, b) => a.price - b.price
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      sorter: (a, b) => a.stock - b.stock
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
      sorter: (a, b) => a.sales - b.sales
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 'on' ? '#52c41a' : '#ff4d4f' }}>
          {status === 'on' ? '上架中' : '已下架'}
        </span>
      ),
      filters: [
        { text: '上架中', value: 'on' },
        { text: '已下架', value: 'out' }
      ],
      onFilter: (value, record) => record.status === value
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
  };

  // 添加商品
  const handleAdd = () => {
    form.resetFields();
    setEditingId(null);
    setVisible(true);
  };

  // 编辑商品
  const handleEdit = (record) => {
    form.setFieldsValue({
      name: record.name,
      categoryId: record.categoryId,
      price: record.price,
      originalPrice: record.originalPrice,
      stock: record.stock,
      status: record.status,
      description: record.description,
      images: record.images
    });
    setEditingId(record.id);
    setVisible(true);
  };

  // 删除商品
  const handleDelete = async (id) => {
     try {
      const updatedProducts = await deleteProduct({ params: { id } });
      setProducts(updatedProducts);
      message.success('商品删除成功');
    } catch (e) {
      message.error('商品删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(async values => {
        setConfirmLoading(true);

        setTimeout(async () => {
          if (editingId) {
            // 更新商品
            const updatedProducts = await updateProduct([{
              id: editingId,
              ...values,
            }]);
            setProducts(updatedProducts);
            message.success('商品更新成功');
          } else {
            // 添加新商品
            const newProduct = {
              ...values,
              id: Date.now(),
              sales: 0,
              images: values.images || [
                getProductPlaceholder(values.name, '200x200')
              ]
            };
            // 这里假设 updateProduct 也能处理新增（如 mock 支持），否则需单独写 addProduct
            const updatedProducts = await updateProduct([newProduct]);
            setProducts(updatedProducts);
            message.success('商品添加成功');
          }

          setVisible(false);
          setConfirmLoading(false);
        }, 1000);
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 处理模态框取消
  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <div className="product-manage">
      <div className="page-header">
        <h2>商品管理</h2>
        <div className="page-header-actions">
          <Input
            placeholder="搜索商品名称"
            prefix={<SearchOutlined />}
            style={{ width: 200, marginRight: 16 }}
            allowClear
            onChange={(e) => handleSearch(e.target.value)}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加商品
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={products}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
      />

      <Modal
        title={editingId ? "编辑商品" : "添加商品"}
        open={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        confirmLoading={confirmLoading}
        maskClosable={false}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          name="productForm"
          initialValues={{ status: 'on' }}
        >
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

          <Form.Item
            name="categoryId"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select placeholder="请选择商品分类">
              {categories.map(category => (
                <Option key={category.id} value={category.id}>{category.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="price"
            label="商品价格"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="请输入商品价格"
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="originalPrice"
            label="原价"
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="请输入商品原价"
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存数量' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入库存数量"
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="商品状态"
            rules={[{ required: true, message: '请选择商品状态' }]}
          >
            <Select placeholder="请选择商品状态">
              <Option value="on">上架</Option>
              <Option value="out">下架</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="商品描述"
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入商品描述"
            />
          </Form.Item>

          <Form.Item
            name="images"
            label="商品图片"
            extra="上传商品图片（功能模拟，实际不会上传）"
          >
            <Upload
              listType="picture"
              beforeUpload={() => false}
              maxCount={5}
            >
              <Button icon={<UploadOutlined />}>选择图片</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductManage; 